package com.xzzz.common.base.util;

import cn.hutool.core.util.ArrayUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.HashMap;

public class AspectUtil {

    /**
     * 获取类名
     *
     * @param joinPoint 切点
     * @return 类名称
     */
    public static String getClassName(ProceedingJoinPoint joinPoint) {
        if (joinPoint == null) {
            return "";
        }
        return joinPoint.getSignature().getDeclaringTypeName();
    }

    /**
     * 获取切点名称，如果切点是方法，获取方法名称
     *
     * @param joinPoint 切点
     * @return 方法名称
     */
    public static String getMethodName(ProceedingJoinPoint joinPoint) {
        if (joinPoint == null) {
            return "";
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod().getName();
    }

    /**
     * 获取指定参数和参数值
     *
     * @param paramName 参数名
     * @return 参数名和参数值的
     */
    public static HashMap<String, Object> getParam(ProceedingJoinPoint joinPoint, String paramName) {
        HashMap<String, Object> result = new HashMap<>();

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] paramNames = methodSignature.getParameterNames();
        int targetIndex = -1;
        for (int i = 0; i < paramNames.length; i++) {
            if (paramNames[i].equals(paramName)) {
                targetIndex = i;
            }
        }

        if (targetIndex >= 0 && ArrayUtil.isNotEmpty(joinPoint.getArgs())) {
            result.put(paramName, joinPoint.getArgs()[targetIndex]);
        }

        return result;
    }
}
